08. Exercise: Override onSizeChanged()

22 07 AAK OnSizeChanged SC

Android Developer Documentation

Exercise

In this exercise you are going to override onSizeChanged().

  1. In MyCanvasView, at the class level, define member variables for a canvas and a bitmap. Call them extraCanvas and extraBitmap. These are your bitmap and canvas for caching what has been drawn before.
private lateinit var extraCanvas: Canvas
private lateinit var extraBitmap: Bitmap
  1. Define a class level variable backgroundColor, for the background color of the canvas and initialize it to the colorBackground you defined earlier.
private val backgroundColor = ResourcesCompat.getColor(resources, R.color.colorBackground, null)
  1. In MyCanvasView, override the onSizeChanged() method. This callback method is called by the Android system with the changed screen dimensions, that is, with a new width and height (to change to) and the old width and height (to change from).
override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) {
   super.onSizeChanged(width, height, oldWidth, oldHeight)
}
  1. Inside onSizeChanged(), create an instance of Bitmap with the new width and height, which are the screen size, and assign it to extraBitmap. The third argument is the bitmap color configuration. ARGB_8888 stores each color in 4 bytes and is recommended.
extraBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
  1. Create a Canvas instance from extraBitmap and assign it to extraCanvas.
 extraCanvas = Canvas(extraBitmap)
  1. Specify the background color in which to fill extraCanvas.
extraCanvas.drawColor(backgroundColor)
  1. Looking at onSizeChanged(), a new bitmap and canvas are created every time the function executes. You need a new bitmap, because the size has changed. However, this is a memory leak, leaving the old bitmaps around. To fix this, recycle extraBitmap before creating the next one.
if (::extraBitmap.isInitialized) extraBitmap.recycle()